package application

import (
	"fmt"
	"zatta-gateway/config"
	"zatta-gateway/pkg/db"
)

func New(opts ...config.AppOption) (*Application, error) {
	options := config.NewApplicationConfig(opts...)
	if options.DBConfigPath == "" {
		return nil, fmt.Errorf("db config path is required")
	}
	// 从 dbConfigPath 里面读取 dbConfig
	dbConfig, err := config.LoadDBConfig(options.DBConfigPath, "db.json")
	if err != nil {
		return nil, fmt.Errorf("failed to load db config: %w", err)
	}
	dbClientManager := db.NewClientManager(dbConfig.ModelDBDNS(), dbConfig.RpcServerDNS())
	if err := dbClientManager.Connect(); err != nil {
		return nil, fmt.Errorf("failed to connect to database: %w", err)
	}
	application := newApplication(options, dbClientManager)
	return application, nil
}
